package com.mashibing.service.impl.redisImpl;

import com.mashibing.internalcommon.dto.ResponseResult;
import com.mashibing.internalcommon.request.DriverGrabRequest;
import com.mashibing.service.GrabService;
import com.mashibing.service.OrderService;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

@Service("grabByRedissonRedLockYmlService")
public class GrabByRedissonRedLockYmlServiceImpl implements GrabService {

    @Autowired
    private OrderService orderService;

    @Autowired
    @Qualifier("redissonRedLockClient1")
    private RedissonClient redissonClient1;

    @Autowired
    @Qualifier("redissonRedLockClient2")
    private RedissonClient redissonClient2;

    @Autowired
    @Qualifier("redissonRedLockClient3")
    private RedissonClient redissonClient3;

    @Autowired
    @Qualifier("redissonRedLockClient4")
    private RedissonClient redissonClient4;

    @Autowired
    @Qualifier("redissonRedLockClient5")
    private RedissonClient redissonClient5;

    @Override
    public ResponseResult grab(DriverGrabRequest driverGrabRequest) {

        String orderIdKey = driverGrabRequest.getOrderId() + "";

        System.out.println("开始锁 redissonRedLockClient");
        RLock rLock1 = redissonClient1.getLock(orderIdKey);
        RLock rLock2 = redissonClient2.getLock(orderIdKey);
        RLock rLock3 = redissonClient3.getLock(orderIdKey);
        RLock rLock4 = redissonClient4.getLock(orderIdKey);
        RLock rLock5 = redissonClient5.getLock(orderIdKey);
        RedissonRedLock lock = new RedissonRedLock(rLock1, rLock2, rLock3, rLock4, rLock5);
        lock.lock();

        // 模拟实际情况测试代码
//        try {
//            TimeUnit.SECONDS.sleep(10);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        ResponseResult responseResult = orderService.driverGrab(driverGrabRequest);
        lock.unlock();
        System.out.println("结束锁 redissonRedLockClient");

        return responseResult;
    }


}
